<template>
  <div class="page-register">
    <article class="header">
      <header>
        <nuxt-link to="/">
          <img src="@/assets/img/logo.png" alt="logo" height="40px" width="100px" />
        </nuxt-link>
        <span class="login" style="margin-top:5px">
          <em class="bold">已有账号？</em>
          <a href="/login">
            <el-button type="primary" size="small" @click="tologin">登录</el-button>
          </a>
        </span>
      </header>
    </article>
    <section>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="昵称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="username">
          <el-input @blur="checkEmail()" v-model="ruleForm.username" /><div class="error">{{ eError }}</div>
          <el-button :disabled="this.disabled" size="mini" round @click="sendMsg">发送验证码</el-button>
          <span class="status">{{ statusMsg }}</span>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="ruleForm.code" maxlength="6" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="cpwd">
          <el-input v-model="ruleForm.cpwd" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="register">同意以下协议并注册</el-button>
          <div class="error">{{ error }}</div>
        </el-form-item>
        <el-form-item>
          <a class="f1" href="http://www.meituan.com/about/terms" target="_blank">《校园网上食堂网用户协议》</a>
        </el-form-item>
      </el-form>
    </section>
  </div>
</template>
<script>
import * as homeApi from '@/server/home.js'
export default {
  layout: "blank",
  data() {
    return {
      timerid: null,
      statusMsg: "",
      disabled: false,
      eError: "",
      error: "",
      ruleForm: {
        name: "",
        code: "",
        password: "",
        cpwd: "",
        username: ""
      },
      rules: {
        name: [
          {
            required: true,
            type: "string",
            message: "请输入昵称",
            trigger: "blur"
          }
        ],
        username: [
          {
            required: true,
            type: "email",
            message: "请输入邮箱",
            trigger: "blur"
          }
        ],
        code: [
          {
            required: true,
            type: "string",
            message: "请输入验证码",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "创建密码",
            trigger: "blur"
          }
        ],
        cpwd: [
          {
            required: true,
            message: "确认密码",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("请再次输入密码"));
              } else if (value !== this.ruleForm.password) {
                callback(new Error("两次输入密码不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    tologin: function() {
      this.$router.push("/login");
    },
    sendMsg: function() {
      const self = this;
      let namePass;
      let emailPass;
      if (self.timerid) {
        return false;
      }
      this.$refs["ruleForm"].validateField("name", valid => {
        namePass = valid;
      });
      self.statusMsg = "";
      if (namePass) {
        return false;
      }
      this.$refs["ruleForm"].validateField("username", valid => {
        emailPass = valid;
      });
      if (!namePass && !emailPass) {
        homeApi.sendEmail(this.ruleForm.username).then(result => {
          if (result.data.code == 200) {
              let count = 60;
              this.disabled = true;
              if (self.timerid != null) {
                clearInterval(self.timerid);
                self.timerid = null;
              }
              self.statusMsg = `验证码已发送,剩余${count--}秒`;
              self.timerid = setInterval(function() {
                self.statusMsg = `验证码已发送,剩余${count--}秒`;
                if (count === 0) {
                  self.disabled = false;
                  clearInterval(self.timerid);
                  self.timerid = null;
                  self.statusMsg = "";
                }
              }, 1000);
            } else {
              this.statusMsg = result.data.message;
            }
        })
      }
    },
    register: function() {
      let self = this;
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          homeApi.register(this.ruleForm).then(result => {
            if(result.data.code == 200) {
              this.$message({
                duration: 1500,
                message: '注册成功，即将跳转到登录页面。。。',
                type: 'success'
              });
              setTimeout(() => {
                this.$router.push("/login");
              }, 1500);
            } else {
              this.error = result.data.message;
            }
          })
        }
      });
    },
    checkEmail: function() {
      homeApi.checkEmail(this.ruleForm.username).then(result => {
        if(result.data.code == 400) {
          this.eError = result.data.message;
        } else {
          this.eError = "";
        }
      })
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/css/register/index.scss";
</style>
